package com.tdam2014.grupo3.adapters;

import java.io.File;
import java.util.ArrayList;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.tdam2014.grupo3.R;
import com.tdam2014.grupo3.entities.People;
import com.tdam2014.grupo3.flickr.util.URLUtils;
import com.tdam2014.grupo3.tasks.ImageDownloadTask;
import com.tdam2014.grupo3.utils.ImagesUtils;

public class PeopleAdapter extends BaseAdapter {
	
	private LayoutInflater inflater;
	private ArrayList<People> peoples;
	private Resources res;
	
	public PeopleAdapter(Context context) {
		this.inflater = LayoutInflater.from(context);
		this.res = context.getResources();
	}

	public void setPeoples(ArrayList<People> peoples) {
		this.peoples = peoples;
	}
	
	public void removeItem(int position) {
		peoples.remove(position);
	}
	
	public void addItem(People people) {
		peoples.add(people);
	}

	@Override
	public int getCount() {
		return peoples.size();
	}

	@Override
	public People getItem(int position) {
		return peoples.get(position);
	}
	
	@Override
	public long getItemId(int position) {
		return -1;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View item = null;
		HolderPeopleItemList holder = null;
		
		if(convertView == null) {
			item = inflater.inflate(R.layout.people_list_item, null);
			holder = new HolderPeopleItemList();
			holder.profileImage = (ImageView) item.findViewById(R.id.imgPeopleProfileImage);
			holder.realName = (TextView) item.findViewById(R.id.txtPeopleRealName);
			holder.data = (TextView) item.findViewById(R.id.txtPeopleData);
			item.setTag(holder);
		} else {
			item = convertView;
			holder = (HolderPeopleItemList) item.getTag();
		}
		
		People people = peoples.get(position);
		
		File profileImage = new File(ImagesUtils.PROFILES_PATH + people.getNsid() + ".jpg");
		if(profileImage.exists()) holder.profileImage.setImageBitmap(BitmapFactory.decodeFile(profileImage.getAbsolutePath()));
		else {
			if(people.getIconServer() > 0) {
				ImageDownloadTask pImageDownloadTask = new ImageDownloadTask(holder.profileImage, true, people.getNsid());
				pImageDownloadTask.execute(URLUtils.getBuddyIconUrl(people.getIconFarm(), people.getIconServer(), people.getNsid()));
			}
		}
		
		holder.realName.setText(people.getRealName());
		if(people.getCountPhotoSets() == 1) holder.data.setText(people.getUsername() + " | " + people.getCountPhotoSets() + " " + res.getString(R.string.album));
		else holder.data.setText(people.getUsername() + " | " + people.getCountPhotoSets() + " " + res.getString(R.string.albums));

		return item;
	}
	
	private class HolderPeopleItemList {
		ImageView profileImage;
		TextView realName;
		TextView data;
	}
}
